import { _decorator, Animation, AnimationClip } from 'cc';
import { PARAMS_NAME_ENUM, TILE_TYPE_ENUM } from '../enums';
import { getInitParamsNumber, getInitParamsTrigget, StateMachine } from '../../base/stateMachine';
import State from '../../base/State';
import IdleSubStateMachine from './idleSubStateMachine';
import TurnLeftSubStateMachine from './turnLeftSubStateMachine';
import TurnRightSubStateMachine from './turnRightSubStateMachine';
const { ccclass, property } = _decorator;

@ccclass('PlayerStateMachine')
export class PlayerStateMachine extends StateMachine {
    async init() {
        this._animationComponent = this.addComponent(Animation);
        this.initParams();
        this.initStateMachines();
        this.initAnimationEvent();

        await Promise.all(this._waitingList);
    }

    initParams(): void {
        this._params.set(PARAMS_NAME_ENUM.IDLE, getInitParamsTrigget());
        this._params.set(PARAMS_NAME_ENUM.TURNLEFT, getInitParamsTrigget());
        this._params.set(PARAMS_NAME_ENUM.TURNRIGHT, getInitParamsTrigget());
        // this._params.set(PARAMS_NAME_ENUM.DEATH, getInitParamsTrigget());
        this._params.set(PARAMS_NAME_ENUM.DIRECTION, getInitParamsNumber());
    }

    initStateMachines(): void {
        this._stateMachines.set(PARAMS_NAME_ENUM.IDLE, new IdleSubStateMachine(this));
        this._stateMachines.set(PARAMS_NAME_ENUM.TURNLEFT, new TurnLeftSubStateMachine(this));
        this._stateMachines.set(PARAMS_NAME_ENUM.TURNRIGHT, new TurnRightSubStateMachine(this));
    }

    initAnimationEvent(): void {
        this._animationComponent.on(Animation.EventType.FINISHED, () => {
            const name = this._animationComponent.defaultClip.name;
            const white_list = ["turn"];
            if (white_list.some(v => name.includes(v)))
                this.setParams(PARAMS_NAME_ENUM.IDLE, true);
        });
    }

    run(): void {
        switch(this.currentState) {
            case this._stateMachines.get(PARAMS_NAME_ENUM.IDLE):
            case this._stateMachines.get(PARAMS_NAME_ENUM.TURNRIGHT):
            case this._stateMachines.get(PARAMS_NAME_ENUM.TURNLEFT):
                if (this._params.get(PARAMS_NAME_ENUM.IDLE).value) {    
                    this.currentState = this._stateMachines.get(PARAMS_NAME_ENUM.IDLE)
                } else if (this._params.get(PARAMS_NAME_ENUM.TURNRIGHT).value) {
                    this.currentState = this._stateMachines.get(PARAMS_NAME_ENUM.TURNRIGHT)
                } else if (this._params.get(PARAMS_NAME_ENUM.TURNLEFT).value) {
                    this.currentState = this._stateMachines.get(PARAMS_NAME_ENUM.TURNLEFT)
                } // else this.currentState = this.currentState;
                break;
            default:
                this.currentState = this._stateMachines.get(PARAMS_NAME_ENUM.IDLE)
                break;
        }
    }

}

